import WebsocketHeartbeatJs from "websocket-heartbeat-js";
let socket = null;
function isJSON(str) {
  if (typeof str == "string") {
    try {
      var obj = eval("(" + str + ")");
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      // console.log('error：' + str + '!!!' + e);
      return false;
    }
  }
}
function isNumber(val) {
  var regPos = /^\d+(\.\d+)?$/; //非负浮点数
  var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  if (regPos.test(val) || regNeg.test(val)) {
    return true;
  } else {
    return false;
  }
}

/**
 * @param {string} url 'ws://xxx'
 * @param {string} 字符串 必填 例如：'{ "ip": "10.10.5.50", "type": "readWhole", "agreement": "mod" }'
 * @param {Function} callback'回调函数'
 */
export function sendSock(url, callback) {
  socket = new WebsocketHeartbeatJs({
    url: url,
    // pingTimeout: 3000,//每 5 秒发送一次心跳。如果收到任何后端消息，计时器将重置 
  });
  socket.onopen = function() {
    console.log("已开启websocket==>");
    socket.send();
    // if (obj) {
    // }
  };
  socket.onmessage = function(e) {
    if (isJSON(e.data)) {
      callback(e.data);
    }else{
      callback(null)
    }
    // callback(e.data);
  };
  socket.onreconnect = function() {
    console.log("链接中...");
  };
  socket.onerror = () => {
    // console.log('connect onerror');
    console.log("链接失败");
  };
}
// 关闭
export function closeSock() {
  if (socket) {
    socket.close();
    console.log("已关闭websocket==>");
  }
}

export function CFSend(data) {
  if (socket) {
    socket.send(data);
  }
}
